package com.zwr.sheller.shop.controller;

import com.zwr.sheller.core.common.BusinessException;
import com.zwr.sheller.core.common.JsonResult;
import com.zwr.sheller.core.common.WDMBusinessException;
import com.zwr.sheller.core.common.WDMExceptionCode;
import com.zwr.sheller.core.pojo.*;
import com.zwr.sheller.shop.mapper.OrderSkuMapper;
import com.zwr.sheller.shop.mapper.OriginOrderMapper;
import com.zwr.sheller.shop.mapper.RefundMapper;
import com.zwr.sheller.shop.mapper.SkuMapper;
import com.zwr.sheller.shop.service.OriginOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

/**
 * @author wdm
 * 后台订单模块的接口集合
 */
@RestController
@RequestMapping(value = "/ordershop")
@Api(tags = "订单管理")
public class OrderController {
    @Autowired(required = false)
    private OriginOrderService originOrderService;
    @Autowired(required = false)
    private OriginOrderMapper originOrdermapper;
    @Autowired(required = false)
    private RefundMapper refundMapper;
    @Autowired(required = false)
    private OrderSkuMapper orderSkuMapper;
    @Autowired(required = false)
    private SkuMapper skumapper;
    @Autowired(required = false)
    private RedisTemplate redisTemplate;


    @PostMapping("/selectOrderByDateAndStatus")
    @ApiOperation("通过条件模糊查询各种状态的订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "订单状态", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "date", value = "日期（字符串形式）", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderNum", value = "订单编号（字符串形式 ，支持模糊查询）", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "goodsName", value = "商品名称（字符串形式 ，支持模糊查询）", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码（每页数据规定为3条）", required = true, dataType = "Integer", paramType = "query"),
    })
    public Map<String , Object>  selectOrderByDateAndStatus(Integer status, String date, String orderNum, String goodsName, Integer page) throws WDMBusinessException {
        List<Map<String, Object>> maps = originOrderService.selectOrderByDateAndStatus(status, date, orderNum, goodsName, page);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("查询成功");
        jsonResult.setField("Data",maps);
        return  jsonResult.getMap();
    }




    @PostMapping("/selectOrderDetail")
    @ApiOperation("查询某个订单的详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderID", value = "订单ID", required = true, dataType = "Long", paramType = "query"),
    })
    public Map<String , Object> selectOrderDetail(Long orderID) throws WDMBusinessException {
        Map<String, Object> map = originOrderService.selectOrderDetailByOrderId(orderID);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("查询订单详情成功");
        jsonResult.setField("Data",map);
        return  jsonResult.getMap();
    }

    @PostMapping("/ConfirmShipment")
    @ApiOperation("订单确认发货")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单Id的集合", required = true, dataType = "List<Long>", paramType = "query"),


    })
    @Transactional(rollbackFor = Throwable.class)
    public  Map<String , Object> confirmOrderStatus( @RequestParam List<Long> orderId  ) throws BusinessException {
        for (Long id : orderId) {
            Example example = new Example(OriginOrder.class);
            example.createCriteria().andEqualTo("orderId",id);
            OriginOrder originOrder = new OriginOrder();
            originOrder.setOrderId(id);
            originOrder.setOrderStatus(3);
            //修改操作
            originOrderService.updateByNewT(originOrder,example);
        }

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("操作成功");
        return  jsonResult.getMap();
    }
    @PostMapping("/queryOrderToBeReceived")
    @ApiOperation("查询待收货订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "date", value = "日期", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deliveryMethod", value = "配送方式", required = true, dataType = "Integer", paramType = "query"),
    })
    public Map<String, Object> queryOrderToBeReceived(String date, Integer deliveryMethod){
        List<Map<String, Object>> maps = originOrderService.queryOrderToBeReceived(date, deliveryMethod);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("操作成功");
        jsonResult.setField("Data",maps);
        return  jsonResult.getMap();
    }





    @PostMapping("/querySelfWithdrawalOrder")
    @ApiOperation("查询自提订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "date", value = "日期（字符串形式）", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderNum", value = "订单编号（字符串形式 ，支持模糊查询）", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "goodsName", value = "商品名称（字符串形式 ，支持模糊查询）", required = false, dataType = "String", paramType = "query"),
    })
    public  Map<String,Object> querySelfWithdrawalOrder(String date, String orderNum, String goodsName){
        List<Map<String, Object>> maps = originOrderService.querySelfWithdrawalOrder(date, orderNum, goodsName);
        //根据收获方式来查询订单，自提订单
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("查询成功");
        jsonResult.setField("Data",maps);
        return  jsonResult.getMap();
    }



    @PostMapping("/checkCode")
    @ApiOperation("核销订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单Id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "checkCode", value = "订单核销码", required = true, dataType = "String", paramType = "query"),
    })
    public Map<String , Object> checkOrder(Long orderId ,String checkCode ) throws BusinessException, WDMBusinessException {
            //通过id查找到订单
        OriginOrder originOrder = originOrdermapper.selectByPrimaryKey(orderId);
        JsonResult jsonResult = new JsonResult();
        //核对核销码 1.正确 2.失败
        if (originOrder.getOrderVerificationCode().equals(checkCode)){
            Example example = new Example(OriginOrder.class);
            example.createCriteria().andEqualTo("orderId",orderId);
            OriginOrder originOrder1 = new OriginOrder();
            originOrder1.setOrderId(orderId);
            originOrder1.setOrderStatus(3);
            originOrderService.updateByNewT(originOrder1,example);
            jsonResult.setCode("1");
            jsonResult.setMsg("核销成功");
            return  jsonResult.getMap();
        }else {
            throw  new WDMBusinessException(WDMExceptionCode.CODE_NOT_SURE);
        }

        }


    @PostMapping("/queryRefoundOrder")
    @ApiOperation("查询各种状态的退货订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "refundStatus", value = "订单状态", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "date", value = "日期（字符串形式）", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderNum", value = "订单编号（字符串形式 ，支持模糊查询）", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "goodsName", value = "商品名称（字符串形式 ，支持模糊查询）", required = false, dataType = "String", paramType = "query"),
    })
     public  Map<String,Object>  queryRefoundOrder(Integer refundStatus, String date, String orderNum, String goodsName){
        List<Map<String, Object>> maps = originOrderService.queryRefoundOrder(refundStatus, date, orderNum, goodsName);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("查询成功");
        jsonResult.setField("Data",maps);
        return  jsonResult.getMap();
     }

    @PostMapping("/checkRefundOrder")
    @ApiOperation("批量审核退货订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderIds", value = "订单Id集合", required = true, dataType = "list", paramType = "query"),
    })
    @Transactional(rollbackFor = Throwable.class)
    public  Map<String,Object> checkRefundOrder(@RequestParam List<Long> orderIds ){
        for (Long orderId : orderIds) {
            Example example = new Example(Refund.class);
            example.createCriteria().andEqualTo("orderId",orderId);
            Refund refund = new Refund();
            refund.setOrderId(orderId);
            refund.setRefundStatus(2L);
            refundMapper.updateByExampleSelective(refund,example);
        }

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("审核成功");
        return  jsonResult.getMap();
    }

    @PostMapping("/refuseRefundOrder")
    @ApiOperation("拒绝处理退货订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单Id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "refuseReason", value = "拒绝处理原因", required = true, dataType = "Long", paramType = "query"),
    })

    public  Map<String,Object> refuseRefundOrder(Long orderId ,String refuseReason ){
        Example example = new Example(Refund.class);
        example.createCriteria().andEqualTo("orderId",orderId);
        Refund refund = new Refund();
        refund.setOrderId(orderId);
        refund.setRefundStatus(5L);
        refund.setRefundRefundReason(refuseReason);
        refundMapper.updateByExampleSelective(refund,example);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("审核成功");
        return  jsonResult.getMap();
    }

    @PostMapping("/refundSkuStock")
    @ApiOperation("退货")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单Id", required = true, dataType = "Long", paramType = "query"),
    })
    @Transactional(rollbackFor = Throwable.class)
    public  Map<String,Object> refundSkuStock(Long orderId  ){
        Example example = new Example(Refund.class);
        example.createCriteria().andEqualTo("orderId",orderId);
        Refund refund = new Refund();
        refund.setOrderId(orderId);
        refund.setRefundStatus(3L);
        refundMapper.updateByExampleSelective(refund,example);
        //操作数据库返还缓存
        Example example1 = new Example(OrderSku.class);
        example1.createCriteria().andEqualTo("orderId",orderId);
        List<OrderSku> orderSkus = orderSkuMapper.selectByExample(example1);
        for (OrderSku skus : orderSkus) {
            Sku sku = skumapper.selectByPrimaryKey(skus.getSkuId());
            sku.setSkuStock(sku.getSkuNum()+skus.getSkuNum());
            skumapper.updateByPrimaryKey(sku);

            //操作缓存
            if (redisTemplate.hasKey("skuId:"+skus.getSkuId())){
                redisTemplate.delete("skuId:"+skus.getSkuId());
            }
        }


        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("退货成功");
        return  jsonResult.getMap();
    }

}
